<?php

if (!defined('IN_IA')) {
    exit('Access Denied');
}

class Withdrawal_MxShopPage extends WebPage {

    public function main() {
        global $_W, $_GPC;
        $this -> orderList(1, 'main');
    }
    
    public function inapply(){
        global $_W, $_GPC;
        $this -> orderList(2, 'ingoing');
    }

    public function finish(){
        global $_W, $_GPC;
        $this -> orderList(3, 'finish');
    }

    public function close(){
        global $_W, $_GPC;
        $this -> orderList(4, 'close');
    }
    
    protected function orderList($status, $action){
        global $_W, $_GPC;
        $uniacid = $_W['platformid'];
        
        $pindex = max(1, intval($_GPC['page']));
        $psize = 20;
        
        $condition = '';

        $paras = array();

        $orderstatus = array(1 => array('css' => 'danger', 'name' => '待审核'), 2 => array('css' => 'warning', 'name' => '待打款'), 3 => array('css' => 'success', 'name' => '已打款'), 4 => array('css' => 'default', 'name' => '失效'));
        
        if($action != 'all'){
            $condition .= ' AND o.status = :status';
            $paras[':status'] = $status;
        }

        if (empty($starttime) || empty($endtime))
        {
            $starttime = strtotime('-1 month');
            $endtime = time();
        }

        $searchtime = trim($_GPC['timetype']);
        if (!(empty($searchtime)) && is_array($_GPC['time']) && in_array($searchtime, array('createtime', 'checktime', 'paytime')))
        {
            $starttime = strtotime($_GPC['time']['starttime']);
            $endtime = strtotime($_GPC['time']['endtime']);
            $condition .= ' AND o.' . $searchtime . ' >= :starttime AND o.' . $searchtime . ' <= :endtime ';
            $paras[':starttime'] = $starttime;
            $paras[':endtime'] = $endtime;
        }
        
        if (!(empty($_GPC['searchfield'])) && !(empty($_GPC['keyword'])))
        {
            $paras[':keyword'] = htmlspecialchars_decode($_GPC['keyword'], ENT_QUOTES);
            if($_GPC['searchfield'] == 'applyno'){
                $condition .= ' AND locate(:keyword,o.drawalsn)>0';
            
            } else if ($_GPC['searchfield'] == 'member'){
                $condition .= ' AND (locate(:keyword,m.realname)>0 or locate(:keyword,m.mobile)>0)';

            }
        }

        $paytype = array('0'=>array('title'=>'余额'), '1'=>array('title'=>'微信'), '2'=>array('title'=>'支付宝'), '3'=>array('title'=>'银行卡'));

        $list = pdo_fetchall('SELECT o.*, m.id as mid, m.avatar as avatar, m.mobile as mobile, m.realname as realname FROM ' . tablename('mx_shop_service_withdrawal') . ' o LEFT JOIN ' .tablename('mx_shop_user') . ' m ON o.uid=m.id WHERE 1 ' . $condition . ' ORDER BY o.id DESC LIMIT '. (($pindex - 1) * $psize) . ',' . $psize, $paras);

        $total = pdo_fetchcolumn('SELECT count(o.id) FROM ' . tablename('mx_shop_service_withdrawal') . ' o LEFT JOIN ' .tablename('mx_shop_user') . ' m ON o.uid=m.id WHERE 1 ' . $condition, $paras);

        $money = pdo_fetchcolumn('SELECT truncate(o.realmoney, 2) FROM ' . tablename('mx_shop_service_withdrawal') . ' o LEFT JOIN ' .tablename('mx_shop_user') . ' m ON o.uid=m.id WHERE 1 ' . $condition, $paras);

        $pager = pagination($total, $pindex, $psize);

        include $this->template('sorder/withdrawal');

    }

    public function detail(){

        global $_W, $_GPC;
        $uniacid = $_W['platformid'];

        $id = intval($_GPC['id']);
        if(empty($id)){
            $this->message('参数有误!');
        }

        $apply = pdo_fetch('SELECT o.*, m.id as mid, m.avatar as avatar, m.mobile as mobile, m.realname as realname, m.weixin as winxin FROM ' . tablename('mx_shop_service_withdrawal') . ' o LEFT JOIN ' .tablename('mx_shop_user') . ' m ON o.uid=m.id WHERE o.id=:id', array(':id'=>$id));
        if(empty($apply)){
            $this->message('该提现申请不存在!');
        }

        $paytype = array('0'=>array('title'=>'余额'), '1'=>array('title'=>'微信'), '2'=>array('title'=>'支付宝'), '3'=>array('title'=>'银行卡'));

        $uid = $apply['uid'];
        $comm = pdo_fetch('SELECT * FROM ' .tablename('mx_shop_service_commission') . ' WHERE uid=:id', array(':id'=>$uid));

        $logtotal = pdo_fetchcolumn('SELECT sum(money) FROM '.tablename('mx_shop_service_commission_log').' WHERE uid=:uid AND type=1 AND isfinish=1', array(':uid'=>$uid));
        $logdrawal = pdo_fetchcolumn('SELECT sum(money) FROM '.tablename('mx_shop_service_commission_log').' WHERE uid=:uid AND type=2 AND isfinish=1', array(':uid'=>$uid));

        $level = $this->getUserLevel($uid);
        $total = $remain = $drawal = $freeze = 0;
        if($level['ismanage']){
            $commission = pdo_fetchall('SELECT * FROM ' .tablename('mx_shop_service_commission') . ' WHERE mendianid IN ( SELECT id FROM '.tablename('mx_shop_mendian').' WHERE manageid=:id)', array(':id'=>$uid));

            if(!empty($commission)){

                $mdids = array();
                foreach ($commission as $item) {
                    $mdids[] = $item['mendianid'];
                    $total += $item['total'];
                    $remain += $item['remain'];
                    $drawal += $item['drawal'];
                    $freeze += $item['freeze'];
                }

                $mdids = implode(',', $mdids);

                $logtotal += pdo_fetchcolumn('SELECT sum(money) FROM '.tablename('mx_shop_service_commission_log').' WHERE mendianid IN ('.$mdids.') AND type=1 AND isfinish=1');
                $logdrawal += pdo_fetchcolumn('SELECT sum(money) FROM '.tablename('mx_shop_service_commission_log').' WHERE mendianid IN ('.$mdids.') AND type=2 AND isfinish=1');

                $comm['total'] += $total;
                $comm['remain'] += $remain;
                $comm['drawal'] += $drawal;
                $comm['freeze'] += $freeze;
            }

        }

        $comm['ispay'] = pdo_fetchcolumn('SELECT sum(money) FROM ' .tablename('mx_shop_service_withdrawal') . ' WHERE uid=:id AND status=2', array(':id'=>$uid));
        $comm['ischeck'] = pdo_fetchcolumn('SELECT sum(money) FROM ' .tablename('mx_shop_service_withdrawal') . ' WHERE uid=:id AND status=1', array(':id'=>$uid));

        include $this->template();

    }

    protected function getUserLevel($uid){

        global $_W;
        $uniacid = $_W['platformid'];

        $owner = pdo_fetchcolumn('SELECT id FROM ' .tablename('mx_shop_service_goods_owner') . ' WHERE uid=:uid AND deleted=0', array(':uid'=>$uid));
        $manage = pdo_fetchcolumn('SELECT id FROM ' .tablename('mx_shop_mendian') . ' WHERE manageid=:uid AND deleted=0', array(':uid'=>$uid));
        $channel = pdo_fetchcolumn('SELECT id FROM ' .tablename('mx_shop_mendian') . ' WHERE channelid=:uid AND deleted=0', array(':uid'=>$uid));
        $prov = pdo_fetchcolumn('SELECT id FROM ' .tablename('mx_shop_operator') . ' WHERE uid=:uid AND type=1 AND deleted=0', array(':uid'=>$uid));
        $area = pdo_fetchcolumn('SELECT id FROM ' .tablename('mx_shop_operator') . ' WHERE uid=:uid AND type=2 AND deleted=0', array(':uid'=>$uid));

        $arr = array(
            'name' => '普通会员',
            'isarea' => 0,
            'isprovince' => 0,
            'ischannel' => 0,
            'ismanage' => 0,
            'isowner' => 0,
        );
        if (!empty($area)){
            $arr['name'] = '区域运营商';
            $arr['isarea'] = 1;

        }

        if (!empty($prov)){
            $arr['name'] = '省级运营商';
            $arr['isprovince'] = 1;

        }

        if (!empty($channel)){
            $arr['name'] = '渠道开拓商';
            $arr['ischannel'] = 1;

        }

        if (!empty($manage)){
            $arr['name'] = '门店店主';
            $arr['ismanage'] = 1;

        }

        if(!empty($owner)){
            $arr['name'] = '创业者';
            $arr['isowner'] = 1;

        }

        return $arr;

    }

    protected function withData(){

        global $_W, $_GPC;

        $id = intval($_GPC['id']);
        if(empty($id)){
            show_json(0,'参数有误!');
        }

        $with = pdo_fetch('SELECT * FROM ' .tablename('mx_shop_service_withdrawal'). ' WHERE id=:id', array(':id'=>$id));
        if(empty($with)){
            show_json(0,'该提现申请不存在!');
        }

        return $with;
    }

    public function check(){

        $with = $this->withData();

        if($with['status'] != 1){
            show_json(0,'该提现申请不需要审核!');
        }

        plog('sorder.withdrawal.check', '提现申请审核提交 ID: ' . $with['id']);

        pdo_update('mx_shop_service_withdrawal', array('status'=>2, 'checktime'=>time()), array('id'=>$with['id']));

        show_json(1);
    }

    public function refuse(){

        global $_W;

        $with = $this->withData();

        if($with['status'] != 1){
            show_json(0,'该提现申请不能驳回!');
        }

        $comlog = pdo_fetchall('SELECT * FROM ' .tablename('mx_shop_service_commission_log'). ' WHERE withid=:id', array(':id'=>$with['id']));
        if(empty($comlog)){
            show_json(0,'该提现申请记录不存在!');
        }

        foreach ($comlog as $item){
            $comm = array();
            if($item['mendianid'] == 0){

                $comm = pdo_fetch('SELECT * FROM ' .tablename('mx_shop_service_commission'). ' WHERE id=:id AND uid=:opid', array(':id'=>$item['comid'], ':opid'=>$item['uid']));

            }else {

                $comm = pdo_fetch('SELECT * FROM ' .tablename('mx_shop_service_commission'). ' WHERE id=:id AND mendianid=:mdid', array(':id'=>$item['comid'], ':mdid'=>$item['mendianid']));

            }

            if(!empty($comm)){

                $remain = $comm['remain'] + $item['money'];
                $freeze = ($comm['freeze'] - $item['money']) > 0 ? ($comm['freeze'] - $item['money']) : 0;

                pdo_update('mx_shop_service_commission', array('remain'=>$remain, 'freeze'=>$freeze), array('id'=>$comm['id']));

            }
        }

        plog('sorder.withdrawal.refuse', '提现申请驳回 ID: ' . $with['id']);

        pdo_update('mx_shop_service_withdrawal', array('status'=>4, 'checktime'=>0, 'invalidtime'=>time()), array('id'=>$with['id']));

        show_json(1);
    }

    public function cancel(){

        $with = $this->withData();

        if($with['status'] != 2){
            show_json(0,'该提现申请不能撤销审核!');
        }

        plog('sorder.withdrawal.check', '提现申请重新审核 ID: ' . $with['id']);

        pdo_update('mx_shop_service_withdrawal', array('status'=>1, 'checktime'=>0), array('id'=>$with['id']));

        show_json(1);

    }

    public function wpay(){

        global $_W;

        $with = $this->withData();

        $uid = $with['uid'];
        if($with['status'] != 2){
            show_json(0,'该提现申请未审核!');
        }

        if($with['realmoney'] < 1){
            show_json(0,'该提现申请不足 1 元!');
        }

        $logmoney = pdo_fetchcolumn('select sum(money)  from ' . tablename('mx_shop_service_commission_log') . ' where withid=:id ', array(':id' => $with['id']));
        if($logmoney < $with['realmoney']){
            show_json(0,'该提现申请金额有误!');
        }

        $logtotal = pdo_fetchcolumn('SELECT sum(money) FROM '.tablename('mx_shop_service_commission_log').' WHERE uid=:uid AND type=1 AND isfinish=1', array(':uid'=>$uid));
        $logdrawal = pdo_fetchcolumn('SELECT sum(money) FROM '.tablename('mx_shop_service_commission_log').' WHERE uid=:uid AND type=2', array(':uid'=>$uid));
        $level = $this->getUserLevel($uid);
        if($level['ismanage']){
            $logtotal += pdo_fetchcolumn('SELECT sum(money) FROM '.tablename('mx_shop_service_commission_log').' WHERE mendianid IN ( SELECT id FROM '.tablename('mx_shop_mendian').' WHERE manageid=:id) AND type=1 AND isfinish=1', array(':id'=>$uid));
            $logdrawal += pdo_fetchcolumn('SELECT sum(money) FROM '.tablename('mx_shop_service_commission_log').' WHERE mendianid IN ( SELECT id FROM '.tablename('mx_shop_mendian').' WHERE manageid=:id) AND type=2', array(':id'=>$uid));
        }

        if($with['realmoney'] > ($logtotal - $logdrawal)){
            show_json(0,'可提现佣金不足 '.$with['realmoney'].' 元！');
        }

        if($with['type'] == 0){

            $info = m('member')->getInfo($with['uid']);
            //提现到余额
            $result = m('userinfo')->setCredit($with['uid'], 'credit2', $with['realmoney'], array($info['id'], '佣金打款'));
            if (is_error($result))
            {
                show_json(0, $result['message']);
            }


        } elseif ($with['type'] == 1){

            //微信
            $result = m('finance')->pay($with['uid'], $with['type'], $with['realmoney'], $with['drawalsn'], '佣金打款');
            if (is_error($result))
            {
                show_json(0, $result['message']);
            }


        }elseif ($with['type'] == 2){

            //支付宝
            $sec = m('common')->getSec();
            $sec = iunserializer($sec['sec']);
            if (!(empty($sec['alipay_pay']['open'])))
            {
                $batch_no_money = $with['realmoney'] * 100;
                $batch_no = 'D' . date('Ymd') . 'CP' . $with['id'] . 'MONEY' . $batch_no_money;
                $res = m('finance')->AliPay(array('account' => $with['alipay'], 'name' => $with['realname'], 'money' => $with['realmoney']), $batch_no, $sec['alipay_pay'], '佣金打款');
                if (is_error($res))
                {
                    show_json(0, $res['message']);
                }
                show_json(1, array('url' => $res));

            }else{
                show_json(0, '支付宝付款未开启！');
            }

        }

        plog('sorder.withdrawal.check', '提现申请打款 ID: ' . $with['id']);

        pdo_update('mx_shop_service_withdrawal', array('status'=>3, 'paytime'=>time()), array('id'=>$with['id']));

        pdo_update('mx_shop_service_commission_log', array('isfinish'=>1, 'finishtime'=>time()), array('withid'=>$with['id']));

        $this->setComm($with['id']);

        show_json(1);
    }

    public function payed(){

        $with = $this->withData();

        if($with['status'] != 2){
            show_json(0,'该提现申请未审核!');
        }

        plog('sorder.withdrawal.check', '提现申请手动打款 ID: ' . $with['id']);

        pdo_update('mx_shop_service_withdrawal', array('status'=>3, 'paytime'=>time()), array('id'=>$with['id']));

        pdo_update('mx_shop_service_commission_log', array('isfinish'=>1, 'finishtime'=>time()), array('withid'=>$with['id']));

        $this->setComm($with['id']);

        show_json(1);
    }

    protected function setComm($withid){

        global $_W;
        $commlog = pdo_fetchall('SELECT * FROM ' . tablename('mx_shop_service_commission_log') . ' WHERE withid=:withid', array(':withid'=>$withid));
        if(!empty($commlog)) {
            foreach ($commlog as $item) {
                $comm = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_service_commission') . ' WHERE id=:id', array(':id' => $item['comid']));
                if (!empty($comm)) {
                    $freeze = ($comm['freeze'] - $item['money']) > 0 ? ($comm['freeze'] - $item['money']) : 0;
                    pdo_update('mx_shop_service_commission', array('drawal' => $comm['drawal'] + $item['money'], 'freeze' => $freeze), array('id' => $comm['id']));
                }
            }
            return;
        }
        return;
    }

}
